﻿using System;
using Lidgren.Network;
using System.Collections.Generic;
using EclipseLib.Shared;
using System.IO;

namespace Server.Management
{
    public static class AccountManager
    {
        // Data Members
        static Dictionary<NetConnection, Account> ActiveAccounts;

        // public Static Methods
        public static void Initialize()
        {
            ActiveAccounts = new Dictionary<NetConnection, Account>(Constants.MaxConnections);

            if(!Directory.Exists(@"Accounts"))
                Directory.CreateDirectory(@"Accounts");
        }
        public static bool AccountBeingUsed(string UserName)
        {
            foreach (KeyValuePair<NetConnection, Account> Entry in ActiveAccounts)
            {
                if (Entry.Value != null)
                    if (Entry.Value.UserName == UserName)
                        return true;
            }

            return false;
        }
        public static bool AccountExists(string UserName)
        {
            return File.Exists(@"Accounts\" + UserName + ".bin");
        }
        public static bool CreateNewAccount(string UserName, string Password, string Email)
        {
            if (AccountExists(UserName))
                return false;
            else
            {
                Account NewAccount = new Account();
                NewAccount.UserName = UserName;
                NewAccount.Password = Password;
                NewAccount.Email = Email;

                NewAccount.ToBinary(@"Accounts\" + UserName + ".bin");

                return true;
            }
        }
        public static bool UseAccount(int Index, string UserName, string Password)
        {
            if (!AccountExists(UserName) || AccountBeingUsed(UserName))
                return false;

            Account NewAccount = new Account();
            NewAccount.FromBinary(@"Accounts\" + UserName + ".bin");

            if (NewAccount.Password != Password)
                return false;

            ActiveAccounts[Network.Socket.Clients[Index]] = NewAccount;
            return true;
        }
        public static Account GetAccount(int Index)
        {
            return ActiveAccounts[Network.Socket.Clients[Index]];
        }
    }
}
